package com.bw.config.security;

import cn.hutool.core.collection.CollectionUtil;
import com.bw.entity.LoginUser;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * 自定义权限决定器
 */
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication auth,
                       Object object,
                       Collection<ConfigAttribute> ca) {

         // 如果所需的角色为匿名 则放行
//        if ( ca.stream().anyMatch(configAttribute -> configAttribute.getAttribute().equals("anonymous"))){
//            return;
//        }
        // 未登录用户先放行，后续过滤器会拦截未登录用户
        if ("anonymousUser".equals(auth.getPrincipal())){
            return;
        }
        //获取当前用户的角色
        LoginUser principal = (LoginUser) auth.getPrincipal();
        List<String> auths = principal.getRoleList();
        // 遍历所需要的角色
        for (ConfigAttribute configAttribute : ca) {
            String attribute = configAttribute.getAttribute();
            for (String role : auths) {
                if (attribute.equals(role)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}

